package com.rzjm.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.DeviceDao;
import com.rzjm.api.dao.DeviceNodeDao;
import com.rzjm.api.dao.ShopDao;
import com.rzjm.api.dao.SysUserDao;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.DeviceService;
import com.rzjm.api.service.SysUserService;
import com.rzjm.api.util.OkHttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, Device> implements DeviceService {

    @Resource
    private DeviceDao dao;
    @Resource
    private DeviceNodeDao deviceNodeDao;

    @Resource
    private SysUserService sysUserService;
    @Resource
    private ShopDao shopDao;

    @Autowired
    ThreadPoolTaskExecutor customAsyncThreadPool;

    @Value("${web.voicePlayUrl}")
    private String voicePlayUrl;//图片地址

    @Override
    public List<Device> getDeviceList(User user, Integer device_type, Integer position, Integer shopId,Integer pageIndex, Integer pageSize) {
        List<Integer> shopIds = new ArrayList<>();
        SysUser sysUser = sysUserService.getSysUserByUser(user);
        if(sysUser!=null){
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",sysUser.getUserId());
            List<Shop> shops = shopDao.getListByUserId(map,0,9999);
            if(CollUtil.isNotEmpty(shops)){
                for (Shop shop : shops){
                    shopIds.add(shop.getId());
                }
            }
        }

        QueryWrapper<Device> qw = new QueryWrapper<>();
        if(shopId > 0){
            qw.eq("shop_id",shopId);
        }else{
            if(shopIds.size() > 0){
                qw.in("shop_id", shopIds);
            }else{
                qw.eq("shop_id",user.getShopId());
            }
        }
        if((device_type == 0 || device_type == 2) && position != null){
            qw.eq("position_type", position);
        }
//        qw.eq("leader_wx_user_id",user.getId());
        qw.and(
                wrapper -> wrapper
                        .eq("device_type", device_type)
                        .or().eq("device_type",2)
                        .or().eq("device_type",3)
                        .or().eq("device_type",4)
        );
        qw.orderByAsc("sort");
        List<Device> list = dao.getPageEntityList(qw, pageIndex, pageSize);
        if(list != null && list.size() > 0){
            for (Device device : list){
                Shop shop = shopDao.selectById(device.getShopId());
                if(shop!=null){
                    device.setShopName(shop.getShopName());
                }

                int isHasPower = 0;
                QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
                qwNode.eq("device_id",device.getId());
                qwNode.eq("position_type", position);
                List<DeviceNode> nodes = deviceNodeDao.selectList(qwNode);
                if(CollUtil.isNotEmpty(nodes)){
                    for (DeviceNode node : nodes){
                        if(node.getDeviceType() == 3){
                            isHasPower ++;
                        }
                    }
                }


                device.setIsHasPower(0);
                if(isHasPower > 0){
                    device.setIsHasPower(1);
                }

                device.setNodes(nodes);
                device.setNodesCount(nodes.size());

            }
        }
        return list;
    }

    @Override
    public void syncDataToIpVoice(Device ipVoice,String voiceUrl) {
        try{

            // 创建一个线程安全的队列
            Queue<Device> queue = new LinkedList<>();
            //指令
            queue.add(ipVoice);

            customAsyncThreadPool.submit(()->{
                synchronized (queue){
                    while (!queue.isEmpty()){
                        Device requestDto1 = queue.poll();

                        String json = "{\"voiceCode\":\""+requestDto1.getDeviceNum()+"\",\"opState\":1,\"voiceUrl\":\""+voiceUrl+"\"}";
                        try {
                            String res = OkHttpClientUtil.getInstance().postJson(voicePlayUrl,json);
                            System.out.println("烟感报警音柱推送" + res);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
